<template>
  <a-card class="card" title="" :bordered="false" >
    <search-form @searching="display"  ref="searchForm" >
    </search-form>
  </a-card>

  <a-card >
    <a-button @click="showModal" type="primary">
      新增
    </a-button>
    <a-modal width="40%" v-model:visible="visible" title="新增学生表信息" @ok="handleOk">
      <a-form
          v-model="form"
          :rules="rules"
          class="form"
          :labelCol="formItemLayout.labelCol"
          :wrapperCol="formItemLayout.wrapperCol"
      >
        <a-row>
          <a-col >
            <a-form-item name="name" label="姓名" >
              <a-input  v-model:value="form.studentName"
                        placeholder="请输入姓名"
              />
            </a-form-item>
          </a-col >
          &nbsp;
          &nbsp;
          <a-col >
            <a-form-item label="学号" name="id">
              <a-input ref="stuId" v-model:value="form.stuId"
                       placeholder="请输入学号"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-item  label="班级" name="clazz">
              <a-input ref="class" v-model:value="form.classs"
                       placeholder="请输入班级"
              />
            </a-form-item>
          </a-col>
          &nbsp;
          &nbsp;
          <a-col >
            <a-form-item  label="性别" name="sex">
              <a-select
                  v-model:value="form.sexx"
                  style="width: 120px"
                  @focus="focus"
                  ref="sex"
                  @change="handleChange"
              >
                <a-select-option value="男">男</a-select-option>
                <a-select-option value="女">女</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <a-table
        :columns="columns"
        :dataSource="data"
        :pagination="true"
        :loading="memberLoading"

    >
      <template v-for="(col, i) in ['name', 'stuId', 'clazz', 'sex']" v-slot:[col]="{ text, record }" >

        <a-input
            :key="col"
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            :placeholder="columns[i].title"
        />
        <template v-else>{{ text }}</template>
      </template>

      <template #operation="{ record }" >
        <span >

            <a @click="showModalMsg(record)">编辑</a>
            <a-modal width="40%" v-model:visible="visibleMsg" title="编辑学生信息" @ok="handleOkStuMsg(record)">
          <a-form :rules="rules" class="form"
                  :labelCol="formItemLayout.labelCol"
                  :wrapperCol="formItemLayout.wrapperCol"
                  v-model="form">
            <a-row>
              <a-col >
                <a-form-item label="姓名" name="name">
                  <a-input v-model:value="form.name" :value="form.name"
                           placeholder="请输入姓名"
                  />
                </a-form-item>
              </a-col >
              &nbsp;
              &nbsp;
              <a-col >
                <a-form-item label="学号" name="id">
                  <a-input v-model:value="form.id" :value="form.id" ref="stuIdChanged"
                           placeholder="请输入学号"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col>
                <a-form-item  label="班级" name="clazz">
                  <a-input v-model:value="form.clazz" :value="form.clazz" ref="classChanged"
                           placeholder="请输入班级"
                  />
                </a-form-item>
              </a-col>
              &nbsp;
              &nbsp;
              <a-col >
                <a-form-item  label="性别" name="sex">
                  <a-select
                      :value="form.sex"
                      v-model:value="form.sex"
                      style="width: 120px"
                      @focus="focus"
                      ref="sexChanged"
                      @change="handleChange"
                  >
                    <a-select-option value="男">男</a-select-option>
                    <a-select-option value="女">女</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-modal>
            <a-divider type="vertical" />
            <a-popconfirm title="是否确定删除？" @confirm="remove(record)">
              <a>删除</a>
            </a-popconfirm>
            <a-divider type="vertical" />
            <a >更多操作</a>
          </span>
      </template>
    </a-table>

  </a-card>

</template>

<script>
import { Row, Col} from 'ant-design-vue';
import { mapState } from 'vuex';
import { cloneDeep } from 'lodash-es';
import {Form, Card, Button, Input, DatePicker, Select, TimePicker, Popover, Table, Popconfirm, Divider, message} from 'ant-design-vue';
import { ExclamationOutlined, CloseCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
import SearchForm from './components/SearchForm.vue';
import FooterToolbar from "../AdvancedForm/components/FooterToolbar";
import {defineComponent, reactive, ref} from 'vue';
import {  toRaw } from 'vue';
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { useForm } from '@ant-design-vue/use';
import { useStore } from 'vuex';
import axios from "axios";
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;



const fieldLabels = {
  name: '仓库名',
  url: '仓库域名',
  owner: '仓库管理员',
  approver: '审批人',
  dateRange: '生效日期',
  type: '仓库类型',
  name2: '任务名',
  url2: '任务描述',
  owner2: '执行人',
  approver2: '责任人',
  dateRange2: '生效日期',
  type2: '任务类型'
};


export default {

  name: 'student',
  components: {
    ARow: Row,
    ACol: Col,
    useForm,
    SearchForm,
    FooterToolbar,
    ATable: Table,
    ADivider: Divider,
    AForm: Form,
    ACard: Card,
    AButton: Button,
    APopover: Popover,
    APopconfirm: Popconfirm,
    ARangePicker: RangePicker,
    ATimePicker: TimePicker,
    AInput: Input,
    AFormItem: FormItem,
    ASelect: Select,
    ASelectOption: Option,
    ExclamationOutlined,
    CloseCircleOutlined,
    PlusOutlined
  },
  computed: {
    ...mapState({
      student: state => {
        console.log('state',state.students);
        return state.students;
      }
    }),


  },
  data () {
    return {
      tempname: '',
      tempid: '',

      form: {
        studentName: '',
        stuId: '',
        classs: '',
        sexx: '',

        name: '',
        id: '',
        clazz: '',
        sex: '',
      },


      visible: ref(false),
      visibleMsg: ref(false),
      //loading: false,
      //memberLoading: false,
      // collapse: false,
      // table
      formItemLayout: {
        labelCol: {
          xs: {span: 24},
          sm: {span: 8},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        }
      },
      rules: {
        name: [{required: true, message: '请输入姓名', whitespace: true, validator: this.checkIsEmpty.bind(this)}],
        id: [{required: true, message: '请输入学号', whitespace: true, validator:this.checkIsEmpty.bind(this)}],
        clazz: [{required: true, message: '请输入班级', whitespace: true,validator:this.checkIsEmpty.bind(this)}],
      },

      columns: [
        {
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
          width: '10%',
          slots: {customRender: 'name'}
        },
        {
          title: '学号',
          dataIndex: 'stuId',
          key: 'stuId',
          width: '20%',
          slots: {customRender: 'stuId'}
        },
        {
          title: '班级',
          dataIndex: 'clazz',
          key: 'clazz',
          width: '20%',
          slots: {customRender: 'class'}
        },
        {
          title: '性别',
          dataIndex: 'sex',
          key: 'sex',
          width: '10%',
          slots: {customRender: 'sex'}
        },
        {
          title: '操作',
          key: 'action',
          slots: {customRender: 'operation'}
        }
      ],
      data: [],
      errors: []

  }
  },
  methods: {

    checkIsEmpty() {
      const name=this.form.name;
      const id=this.form.id;
      const classes=this.form.clazz;
      const sex=this.form.sex;
      console.log(name);
      if (name === ''||id===''||classes===''||sex==='') {
        return Promise.reject('could not be empty.');
      } else {
        return Promise.resolve();
      }
    },

    showModal() {
      this.visible = true;
    },

    showModalMsg(record){
      this.visibleMsg = true;

      const {  name, stuId, clazz, sex } = record;
      this.tempname = name;
      this.tempid = stuId;
      this.form.name = name;
      this.form.sex = sex;
      this.form.id = stuId;
      this.form.clazz = clazz;
    },

    handleOk() {
      //console.log(e);
      //console.log(this.studentName);

      if(this.form.studentName===''||this.form.stuId===''||this.form.classs===''||this.form.sexx===''){
        confirm("请输入完整的信息");
        return;
      }
      const newStudent = {
        name:this.form.studentName,
        id:this.form.stuId,
        class: this.form.classs,
        sex: this.form.sexx
      };
      axios.post('/api/add',newStudent).then(res=>{
        console.log(res.data);
        const result = [];
        let k = 1;
        for (let i = 0; i < res.data.length; i++) {
          const item = {
            key:k++,
            name: res.data[i].name,
            stuId: res.data[i].id,
            editable: false,
            clazz: res.data[i].class,
            sex: res.data[i].sex
          }
          result.push(item);
        }
        result.sort(sortData);
        function sortData(a, b) {
          return b.stuId - a.stuId;
        }
        this.data = result;
        //console.log(this.studentName);
      });
      //this.vStore.dispatch('addStudent',{data:newStudent});
      this.visible = false;
    },
    handleOkStuMsg (record) {
      if(this.form.name===''||this.form.id===''||this.form.clazz===''||this.form.sex===''){
        confirm("请输入完整的信息");
        return;
      }
      console.log("name:"+this.name);
      const Stu = {
        name:this.tempname,
        id:this.tempid,
      };
      axios.post('/api/del',Stu).then(res=>{
        console.log(res.data);
        const result = [];
        let k = 1;
        for (let i = 0; i < res.data.length; i++) {
          const item = {
            key:k++,
            name: res.data[i].name,
            stuId: res.data[i].id,
            editable: false,
            clazz: res.data[i].class,
            sex: res.data[i].sex
          }
          result.push(item);
        }

        const newStudent = {
          name:this.form.name,
          id:this.form.id,
          class: this.form.clazz,
          sex: this.form.sex
        };
        axios.post('/api/add',newStudent).then(res=>{
          console.log(res.data);
          const result = [];
          let k = 1;
          for (let i = 0; i < res.data.length; i++) {
            const item = {
              key:k++,
              name: res.data[i].name,
              stuId: res.data[i].id,
              editable: false,
              clazz: res.data[i].class,
              sex: res.data[i].sex
            }
            result.push(item);
          }
          result.sort(sortData);
          function sortData(a, b) {
            return b.stuId - a.stuId;
          }

          this.data = result;
          //console.log(this.studentName);
        });

        //this.data = result;
        //console.log(this.studentName);
      });



      this.visibleMsg = false;
    },
    remove (record) {
      //const newData = this.data.filter(item => item.key !== key);
      //this.data = newData;
      const {  name, stuId, clazz, sex } = record;
      console.log(name);
      const Stu = {
        name:name,
        id:stuId,
      };
      axios.post('/api/del',Stu).then(res=>{
        console.log(res.data);
        const result = [];
        let k = 1;
        for (let i = 0; i < res.data.length; i++) {
          const item = {
            key:k++,
            name: res.data[i].name,
            stuId: res.data[i].id,
            editable: false,
            clazz: res.data[i].class,
            sex: res.data[i].sex
          }
          result.push(item);
        }
        result.sort(sortData);
        function sortData(a, b) {
          return b.stuId - a.stuId;
        }
        this.data = result;
        //console.log(this.studentName);
      });
    },
    display(datas){
      //sessionStorage.clear();
      console.log(datas[0]);//name || clazz
      console.log(datas[1]);//id   || sex
      //console.log(this.vStore);
      //let info2 =JSON.parse(sessionStorage.getItem('stuinfo'));
      //console.log(info2);
      axios.post('/api/search',datas).then(res=>{
        const result = [];
        let k = 1;
        for (let i = 0; i < res.data.length; i++) {
          const item = {
            key: k++,
            name: res.data[i].name,
            stuId: res.data[i].id,
            editable: false,
            clazz: res.data[i].class,
            sex: res.data[i].sex
          }
          result.push(item)
        }
        result.sort(sortData);
        function sortData(a, b) {
          return b.stuId - a.stuId;
        }
        this.data = result;
        console.log(res.data);
      })


      //this.vStore.dispatch('getStudentInfo',{data:datas});
      //console.log(this.vStore.state);
      //let infon = sessionStorage.getItem('stuinfo');



      /*const stuinfo = this.vStore;
      const stu = this.;
      console.log(stuinfo);
      console.log(stu);*/

    }
  },
  watch:{
    /*info(old,newValue){
      console.log(newValue);
      let info = JSON.parse(newValue);
      console.log(info);

      //const info =JSON.parse(sessionStorage.getItem('stuinfo'));
      console.log(info[0]);
      let k = 1;
      const res = [];
      for (let i = 0; i < info.length; i++) {
        const item = {
          key: k++,
          name: info[i].name,
          stuId: info[i].id,
          editable: false,
          clazz: info[i].class,
          sex: info[i].sex
        }
        res.push(item)
      }
      this.data = res;
    }*/
  },
  created() {
    axios.post('/api/search',["",""]).then(res=>{
      const result = [];
      let k = 1;
      for (let i = 0; i < res.data.length; i++) {
        const item = {
          key: k++,
          name: res.data[i].name,
          stuId: res.data[i].id,
          editable: false,
          clazz: res.data[i].class,
          sex: res.data[i].sex
        }
        result.push(item)
      }
      result.sort(sortData);
      function sortData(a, b) {
        return b.stuId - a.stuId;
      }
      this.data = result;
      console.log(res.data);
    })
  }

}

</script>

<style lang="less" scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>